import axios from 'axios'
import {showFailToast} from 'vant'
import router from '@/router'
import useToken from "@/hooks/useToken";

const baseURL = import.meta.env.VITE_APP_BASE_API;

const service = axios.create({
    baseURL: baseURL,
    timeout: 10 * 1000,
    headers: {
        post: {
            "Content-Type": 'application/json;charset=utf-8'
        }
    }
})
service.interceptors.request.use((config) => {
    const {token} = useToken();
    if (token.value) {
        config.headers['token'] = token.value;
    }
    return config;
})
// interceptors 是拦截器，每个请求都会经过这个拦截器，返回的数据可以通过拦截处理后返回
service.interceptors.response.use(res => {
    if (typeof res.data !== 'object') {
        showFailToast('服务端异常！')
        return Promise.reject(res)
    }
    if (res.data.code != 0) {
        if (res.data.message) showFailToast(res.data.message)
        if (res.data.code == 416) {
            // 返回 416 代表没有登录状态，路由跳转到/login 页面
            router.push({path: '/login', query: {redirect: router.currentRoute.value.fullPath}})
        }
        return Promise.reject(res.data)
    }

    return res.data
})

export default service
